#include <stdio.h>
#include "kfifo.h"
#include "main.h"	
#include "msg.h"
#include "key.h"
#include "tim.h"
#include "sw_timer.h"
#include "adc.h"
#include "ntc.h"
#include "app_user.h"
#include "tim.h"
#include "config.h"


//PC2 NTC
//PC3 NTC_VCC

static uint8_t ntc_state = 0;
static uint8_t ntc_en = 0;

extern APP_INFO app_info;


void app_ntc_gpio_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    /* GPIO Ports Clock Enable */
    __HAL_RCC_GPIOC_CLK_ENABLE();
    
    /*Configure GPIO pin Output Level */
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_RESET);

    /*Configure GPIO pins : PC3*/
    GPIO_InitStruct.Pin = GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}

void app_ntc_vcc_enable(void)
{
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_SET);
}

void app_ntc_vcc_disable(void)
{
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_RESET);
}

void app_charge_en(uint8_t en)
{
    if(en == 0)
        HAL_TIM2_pwm_set(100);
    else
        HAL_TIM2_pwm_set(0);
}

void get_ntc_temperature(void)
{
    uint32_t adc_volue = get_adc_value();

    BOX_LOG("ntc temp: %d\n", adc_volue);
    if(adc_volue < 1500)
    {
        //>60`C
        if(ntc_state != NTC_HIGH_TEMP)
        {
            ntc_state = NTC_HIGH_TEMP;
            app_msg_send(MSG_NTC_HIGH_TEMP);
            if(app_info.bat_state == CHARGE_RUN)
            {
                app_charge_en(0);
            }
        }
    }
    else if(adc_volue > 2000)
    {
        //< 0`C
        if(ntc_state != NTC_LOW_TEMP)
        {
            ntc_state = NTC_LOW_TEMP;
            app_msg_send(MSG_NTC_LOW_TEMP);
            if(app_info.bat_state == CHARGE_RUN)
            {
                app_charge_en(0);
            }
        }
    }
    else
    {
        if(ntc_state != NTC_IDLE)
        {
            ntc_state = NTC_IDLE;
            app_msg_send(MSG_NTC_IDLE);
            if(app_info.bat_state == CHARGE_RUN)
            {
                app_charge_en(1);
            }
        }
    }
}

void app_ntc_handle(void)
{
    if(ntc_en == 0)
        return;
    
    app_ntc_vcc_enable();
    get_ntc_temperature();
    app_ntc_vcc_disable();
}


void app_ntc_init(void)
{
#if (SUPPORT_NTC)
    ntc_en = 1;
    app_ntc_gpio_init();
    app_ntc_vcc_disable();
#endif
}

void app_ntc_deinit(void)
{
    ntc_en = 0;
}


